<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\SendMessage;
use App\Model\HomeUserCaptcha;
use App\Model\HomeUserModel;
use App\Model\HomeUserBeforpass;
use Illuminate\Support\Facades\Redis;
use App\Http\Requests\ForGetPasswordValidata;

class ForGetPasswordController extends Controller
{
    /**
     * 更改密码处理方法
     */
    public function DoChangePassword(ForGetPasswordValidata $request)
    {
        // 查询该用户的验证码
        $captcha = HomeUserCaptcha::where([
            ['captchaIndex', '=', $request->phone],
            ['type', '=', 3],
          ])
          ->orderBy('validperiod', 'desc')
          ->first();

        // 判断该用户是否非法
        if(empty($captcha)) {
            return redirect()->route('home.login')->with('message', '服务器繁忙请重试!');
        }

        // 判断验证码是否超时
        if ($captcha->validperiod < time()) {
            $result = HomeUserCaptcha::where([
                ['captchaIndex', '=',$request->phone],
                ['type', '=', 3],
            ])->delete();
            return redirect()->route('home.login')->with('message', '验证码超时，请重新获取!');
        }

        // 判断验证码是否正确
        if ($request->code == $captcha->captcha) {

            // 查询该用户
            $mysqluser = HomeUserModel::where('phone', $request->phone)->get();

            // 判断是否有该用户
            if (!isset($mysqluser[0])) {
                return redirect()->route('home.forgetpassword')->with('message', '服务器繁忙，请重试!');
            }

            // 判断更改后的面与目前的密码相同
            if ($request->input('newpassword') == $mysqluser[0]->passname) {
                return redirect()->route('home.forgetpassword')->with('message', '更改后的面不能与目前密码相同!');
            }

            // 准备要修改添加的数据
            // 记录过去密码
            HomeUserBeforpass::insert([
              'user_id'    => $mysqluser[0]->id,
              'befor_pass' => $mysqluser[0]->passname,
            ]);

            // 更改密码
            HomeUserModel::where('id', $mysqluser[0]->id)
            ->update([
                  'passname' => password_hash($request->input('password'), PASSWORD_DEFAULT),
            ]);
            // 准备redis键名
            $userkey = 'home_user_hash_phone:'.$request->phone;

            // 在redis中查找该用户
            $redisuser = Redis::hGetAll($userkey);

            // 判断redis中是否有该用户
            if ($redisuser) {
                Redis::Delete($userkey);
                Redis::hMSet($userkey, [
                  'id'         => $mysqluser[0]->id,
                  'username'   => $mysqluser[0]->username,
                  'passname'   => password_hash($request->input('password'), PASSWORD_DEFAULT),
                  'sex'        => $mysqluser[0]->sex,
                  'pic'        => $mysqluser[0]->pic,
                  'email'      => $mysqluser[0]->email,
                  'phone'      => $mysqluser[0]->phone,
                  'user_status'=> $mysqluser[0]->user_status,
                  'member'     => $mysqluser[0]->member,
                  'created_at' => $mysqluser[0]->createtime,
                ]);
            }

            // 退出登录
            $request->session()->forget('Homeuser-data');
            return redirect()->route('home.login');
        }
        // 验证码错误
        return redirect()->route('home.forgetpassword')->with('message', '验证码错误!');
    }

    /**
     * 修改密码验证信息发送方法
     */
    public function ChangePasswordValidata(Request $request)
    {
      // 查询该用户的验证码
      $captcha = HomeUserCaptcha::where([
          ['captchaIndex', '=', $request->phone],
          ['type', '=', 3],
        ])
        ->orderBy('validperiod', 'desc')
        ->first();

        if ($captcha) {

            // 判断是否手贱
            if ($captcha->validperiod > time()) {
                return 403;
            }
        }

        // 获取对象
        $send = new SendMessage;

        // 调用方  法发送验证码
        $result = $send->SendPhoneMessage($request->phone, 3);
        // 判断是否发送成功
        if ($result['status'] == "200") {
            // 成功时把验证信息添加到表内
            HomeUserCaptcha::insert([
                'captchaIndex'=> $request->phone,
                'captcha'     => $result['captcha'],
                'validperiod' => $result['validperiod'],
                'type'        => $result['type'],
            ]);

        }

        // 返回状态码
        return $result['status'];
    }

    /**
     * 判断用户验证码是否正确
     */
    public function ValidataChangePass(Request $request)
    {
        // 查询该用户的验证码
        $captcha = HomeUserCaptcha::where([
              ['captchaIndex', '=', $request->phone],
              ['type', '=', 3],
          ])
          ->orderBy('validperiod', 'desc')
          ->first();
        // 判断该用户是否有获取验证码
        if (!$captcha) {
            return 500;
        }

        // 判断验证码是否超时
        if ($captcha->validperiod < time()) {
            return 403;
        }

        // 判断是否验证成功
        if ($request->code == $captcha->captcha) {
            // 验证成功
            return 200;
        }
        // 验证码错误
        return 500;
    }
}
